import os
from flask import Flask, render_template,request,escape
from vsearch import search4letters
from flask import Flask, render_template, redirect, request, url_for, flash, session
from functools import wraps

users = [
    {
        'username': 'root',
        'password': 'root'
    },
    {
        'username': 'westos',
        'password': 'westos'
    }
]

app = Flask(__name__)
# 设置secret值，保护信息不被泄露
app.config['SECRET_KEY'] = 'aasswde'

def is_login(f):
    """用来判断用户是否登录成功"""

    # 保证函数在加了装饰器之后返回的不是wrapper函数名，而是原函数名
    @wraps(f)
    def wrapper(*args, **kwargs):
        # 判断session对象中是否有seesion['user'],
        # 如果包含信息， 则登录成功， 可以访问主页；
        # 如果不包含信息， 则未登录成功， 跳转到登录界面;
        if session.get('user', None):
            return f(*args, **kwargs)
        else:
            flash('用户必须登陆才能访问%s' % f.__name__)
            return redirect(url_for('login'))

    return wrapper


def is_admin(f):
    """用来判断用户是否登录成功"""

    @wraps(f)
    def wrapper(*args, **kwargs):
        # 判断session对象中是否有seesion['user']等于root,
        # 如果包含信息， 则登录成功， 可以访问主页；
        # 如果不包含信息， 则未登录成功， 跳转到登录界面;；
        if session.get('user', None) == 'root':
            return f(*args, **kwargs)
        else:
            flash('只有管理员root才能访问%s' % f.__name__)
            return redirect(url_for('login'))

    return wrapper



@app.route('/', methods=['GET', 'POST'])
def login():
    title = "vicky|login"
    if request.method == 'POST':
        username = request.form.get('username', None)
        password = request.form.get('password', None)
        # for user in users:
        #     if user['username'] == username and user['password'] == password:
        #         #  将用户登录的信息存储到session中;
        #         # session['user'] = username
        #         return redirect(url_for('index'))
        #     if user['username'] == username and user['password'] != password:
        #         # 出现一个闪现信息;
        #         flash('%s用户密码错误，请重新登陆....' % (username))
        #         return redirect(url_for('login'))
        # else:
        #     flash('%s，您还未注册账号，请先进行注册' % username)
        #     return redirect(url_for('login'))
    return render_template('auth_login_boxed.html',
                           the_title=title, )

@app.route('/register', methods=['GET', 'POST'])
def register():
    title = "vicky|register"
    if request.method == 'POST':
        username = request.form.get('username', None)
        password = request.form.get('password', None)

        # 当所有的信息遍历结束， 都没有发现注册的用户存在， 则将注册的用户添加到服务器， 并跳转登录界面;
        # for user in users:
        #     if user['username'] == username:
        #         return render_template('auth_login_boxed.html', messages='用户%s已经存在' % username)
        # else:
        #     users.append(dict(username=username, password=password))
        #     # 出现一个闪现信息;
        #     flash('%s,您已注册成功，请登陆您的账号' % username, category='info')
        #     return redirect(url_for('login'))
    return render_template('auth_register_boxed.html',
                           the_title=title, )
#用户日志的管理页面
@app.route('/viewlog.html')
def view_the_log() ->'html':
    '''Display the contents of the log file as a HTML table.'''
    contents = []
    with open('vsearch.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))

    len(contents)
    titles = ('用户提交','Remote_addr','代理商','Result')
    return  render_template('viewlog.html',
                            the_title ='日志系统后台',
                            the_data = contents)

@app.route('/auth_lockscreen_boxed.html')
def auth_lockscreen():
    title = "vicky|auth_lockscreen"
    return render_template('auth_lockscreen_boxed.html',
                           the_title=title, )

@app.route('/auth_pass_recovery_boxed.html')
def auth_passrecovery():
    title = "vicky|auth_pass_recovery"
    return render_template('auth_pass_recovery_boxed.html',
                           the_title=title, )

@app.route('/index.html')
def index():
    title = "vicky|analytics"
    return render_template('index.html',
                           the_title=title, )

@app.route('/apps_chat.html')
def app_chart():
    title = "vicky|apps_chat"
    return render_template('apps_chat.html',
                           the_title=title, )

@app.route('/apps_todoList.html')
def apps_todoList():
    title = "vicky|apps_todoList"
    return render_template('apps_todoList.html',
                           the_title=title, )

@app.route('/apps_mailbox.html')
def apps_mailbox():
    title = "vicky|apps_mailbox"
    return render_template('apps_mailbox.html',
                           the_title=title, )

@app.route('/apps_contacts.html')
def apps_contacts():
    title = "vicky|apps_contacts"
    return render_template('apps_contacts.html',
                           the_title=title, )

@app.route('/apps_notes.html')
def apps_notes():
    title = "vicky|apps_notes"
    return render_template('apps_notes.html',
                           the_title=title, )

@app.route('/apps_calendar.html')
def apps_calendar():
    title = "vicky|apps_calendar"
    return render_template('apps_calendar.html',
                           the_title=title, )

@app.route('/user_profile.html')
def auth_pass_recovery():
    title = "vicky|user_profile"
    return render_template('user_profile.html',
                           the_title=title, )


@app.route('/user_account_setting.html')
def user_account_setting():
    title = "vicky|user_account_setting"
    return render_template('user_account_setting.html',
                           the_title=title, )

@app.route('/auth_login_boxed.html')
def auth_login():
    title = "vicky|login"
    return render_template('auth_login_boxed.html',
                           the_title=title, )

if __name__ == '__main__':
    app.run()
